<template>
  <div class="addTemplate-container">
    <div class="addTemplate-content-box">
      <TemplateList
        :list="dataSource"
        templateType="2"
        sendId="getTheId"
        ref="TemplateListRef"
      ></TemplateList>
    </div>

    <div style="height: 20px"></div>

    <!-- <div style="margin: 5px 0; display: flex; align-items: center">
      <span>选择推送：</span>
      <a-select
        style="width: 150px"
        placeholder="请选择分组"
        v-model:value="groupId"
        @change="selectGroup"
      >
        <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
          {{ item.groupName }}
        </a-select-option>
      </a-select>
      <a-select
        style="width: 50%; margin-left: 5px"
        placeholder="请选择"
        mode="multiple"
        v-model:value="sendRobat"
        @change="selectSendRobat"
        allowClear
        show-search
        :options="optionList"
        :filter-option="filterOption"
      >
        <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
          {{ item.label }}
        </a-select-option>
      </a-select>
      <a-button type="primary" style="margin-left: 10px" @click="sendOk">确认推送</a-button>
    </div> -->
    <!-- 添加模板的弹框 -->
    <Modal
      :width="600"
      :height="600"
      :title="title"
      ref="modalRef"
      @onConfirmAdd="handleConfirmAddName"
    >
      <template #contentValue>
        <a-input v-model:value.lazy="templateName" autofocus placeholder="模板名称" />
      </template>
    </Modal>

    <!-- 规则详情 -->

    <Modal
      :width="screenWidth"
      :height="screenHeight"
      title="规则详情"
      ref="modalRuleRef"
      @onConfirmAdd="modalRuleRef.setVisible(false)"
    >
      <template #contentValue>
        <RuleList :templateId="templateId" ref="modalRuleContentRef" :type="type"></RuleList>
      </template>
    </Modal>
  </div>
</template>
<script setup lang="ts">
import * as accountApi from '../../../api/account'
import * as TemplateApi from '../../../api/template.ts'
import { ref, onMounted, toRefs, watch } from 'vue'
import { message } from 'ant-design-vue'
import TemplateList from '../../../components/templateList/index.vue'

import Modal from '../../../components/Modal/index.vue'
import RuleList from '../components/ruleList.vue'
const title = ref('添加模板')
const modalRef = ref()
const modalRuleRef = ref()
const modalRuleContentRef = ref()
const templateName = ref('') //模板名称
const templateType = ref(0)
const TemplateListRef = ref(null)
const props = defineProps({
  screenWidth: Number,
  screenHeight: Number,
  type: Number,
})

const templateId = ref('') // 模板Id
watch(templateId, (newValue, oldValue) => {
  if (newValue) {
    templateId.value = newValue
  }
})

const emit = defineEmits(['sendTheID'])

const getTheId = id => {
  console.log('id=', id)

  emit('sendTheID', id)
}

const { screenWidth, screenHeight, type } = toRefs(props)

//添加模板名称
const handleConfirmAddName = async () => {
  if (!templateName.value) {
    message.error('模板名称不能为空~')

    return
  }
  if (templateType.value) {
    try {
      let {
        state,
        data,
        message: msg,
      } = await TemplateApi.EditTemplate({
        name: templateName.value,
        id: itemInfo.value.id,
      })
      if (state === 200) {
        message.success('修改成功~')
        modalRef.value.setVisible(false)
        getList()
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  } else {
    try {
      let {
        state,
        data,
        message: msg,
      } = await TemplateApi.addTemplate({
        name: templateName.value,
        type: 2,
      })
      if (state === 200) {
        message.success('添加成功~')
        modalRef.value.setVisible(false)
        getList()
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  }
}

const columns = [
  //   {
  //     title: 'ID',
  //     key: 'id',
  //     width: 100,
  //   },
  {
    title: '模板名称',
    key: 'name',
    width: 180,
  },
  {
    title: '类型',
    key: 'type',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
  },
]

const loading = ref(false)
const dataSource = ref([])
const itemInfo = ref({}) //每一条数据
watch(dataSource.value, (newValue, oldValue) => {}, { immediate: true, deep: true })
onMounted(() => {
  getList()
  getRobatList()
  getGroupList()

  // console.log(TemplateListRef.value,"TemplateListRef.valueTemplateListRef.value");
})

//获取当前的 模板列表
const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await TemplateApi.getSimpleTemplateList({ type: 2 })
    if (state === 200) {
      dataSource.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求发送失败1~')
  }
  loading.value = false
}

//删除模板消息
const deleteTemplate = async (record: any) => {
  try {
    const { state, message: msg } = await TemplateApi.deleteTemplate({
      id: record.id,
      type: record.type,
    })
    if (state === 200) {
      message.success('删除成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

//编辑按钮
const Edit = (e: any) => {
  itemInfo.value = e
  templateType.value = 1
  title.value = '编辑模板名称'

  templateName.value = itemInfo.value.name
  modalRef.value.setVisible(true)
}

//添加按钮
const add = () => {
  title.value = '添加模板'
  templateName.value = ''
  templateType.value = 0
  modalRef.value.setVisible(true)
}

// 模板详情
const detail = (e: any) => {
  templateId.value = e.id
  modalRuleRef?.value.setVisible(true)
  // modalRuleContentRef?.value.getList()
  // modalRuleContentRef?.value.getRobatList()
  // modalRuleContentRef?.value.getGroupList()
}

// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  if (selectedRows.length > 1) {
    return
  }
  if (selectedRows.length > 0) {
    templateId.value = selectedRows[0]?.id
  }
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
  console.log(selectedRowKeys, selectedRows)
}

// 拉取机器人列表
let okRobat = ref<string>()
const robatList = ref<SelectProps['options']>([])

interface OptionList {
  label: string
  value: string
}
let optionList = ref<Array<OptionList>>([])
const getRobatList = async () => {
  if (type.value == 1) {
    const params = {
      currentPage: 1,
      pageSize: 100,
    }
    try {
      let { state, data, message: msg } = await accountApi.getList(params)
      if (state === 200) {
        robatList.value = data.list
        optionList.value = data.list.map((item: any) => {
          return {
            label: item.nickName,
            value: item.id,
          }
        })

        optionsArr.value = data.list
        if (data.list.length == 0) {
          if (dataSource.value.length == 0) {
            // activeKey.value = '2'
          }
        } else if (data.list.length > 0) {
          selectRobat(data.list[0].id)
        }
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求发送失败2~')
    }
  } else {
    const params = {
      currentPage: 1,
      pageSize: 100,
    }
    try {
      let { state, data, message: msg } = await accountApi.getFishRobotList(params)
      if (state === 200) {
        robatList.value = data.list
        optionList.value = data.list.map((item: any) => {
          return {
            label: item.nickName,
            value: item.id,
          }
        })

        optionsArr.value = data.list
        // if (data.list.length == 0) {
        //   message.error('闲鱼：无平台账号，请先添加平台账号')
        // } else if (data.list.length > 0) {
        //   // selectRobat(data.list[0].id)
        // }
      } else {
        message.error(msg)
      }
    } catch (error) {
      console.log(error, 'error')

      message.error('网络请求发送失败3~')
    }
  }
}
const selectRobat = (selectValue: unknown) => {
  okRobat.value = selectValue as string
  // searchParams.value.robotId = okRobat.value
  getList()
}

// 推送
const groupList = ref<SelectProps['options']>([])
const groupId = ref<string>()
const optionsArr = ref<SelectProps['options']>([])
const getGroupList = async () => {
  if (type.value == 1) {
    try {
      let { state, data, message: msg } = await accountApi.getWechatRobotGroupList()
      if (state === 200) {
        groupList.value = data
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求发送失败4~')
    }
  } else {
    try {
      let { state, data, message: msg } = await accountApi.getFishRobotGroupList()
      if (state === 200) {
        groupList.value = data
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求发送失败5~')
    }
  }
}
const selectGroup = (selectValue: any) => {
  groupId.value = selectValue as string
  sendRobat.value = optionsArr
    .value!.filter(item => item.groupId == groupId.value)
    .map(item => item.id)
}

// 推送配置
let sendRobat = ref<Array<string>>()
const selectSendRobat = (selectValue: any) => {
  sendRobat.value = selectValue
}
const pushRobot = async () => {
  // console.log('okRobat=', okRobat.value)
  if (!templateId.value) {
    message.error('请选择模板')
    return
  }
  let params = {
    acceptRobotIds: sendRobat.value,
    channel: type.value,
    groupId: templateId.value,
  }
  try {
    const { state, message: msg } = await TemplateApi.pushTemplateZyRule(params)
    if (state === 200) {
      message.success('操作成功')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// select搜索
const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}
//推送
const sendOk = () => pushRobot()

const dispthChild = () => {
  TemplateListRef?.value.getList()
}

defineExpose({
  dispthChild,
})
</script>
<style lang="less" scoped>
.addTemplate-container {
  .addTemplate-content-box {
    .content {
      width: 80%;
      li:nth-child(n + 2) {
        margin-top: 5px;
      }
      li {
        list-style: none; /* 简写形式 */
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        // background-color: blue;
        background: rgba(255, 255, 255, alpha);
        padding: 20px;
        box-sizing: border-box;
      }
    }
  }

  .btn {
    margin-bottom: 20px;
  }
}
</style>
